package com.caiyi.financial.nirvana.sms.cmpp.hander;

import com.caiyi.financial.nirvana.sms.cmpp.CMPPHeader;
import com.caiyi.financial.nirvana.sms.cmpp.CMPPMessageTool;
import com.caiyi.financial.nirvana.sms.cmpp.CharsetInfo;
import com.caiyi.financial.nirvana.sms.cmpp.message.CMPP3Message;
import com.caiyi.financial.nirvana.sms.cmpp.message.body.*;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;

public class CmppServerHandler extends SimpleChannelInboundHandler<CMPP3Message> {
    private static final Logger logger = LoggerFactory.getLogger(CmppServerHandler.class);
    private static final AtomicLong MESSAGEIDSEED = new AtomicLong();
    private int account;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, CMPP3Message msg) throws Exception {
        int commandId = msg.getCommandID();
        switch (commandId) {
            case CMPP3Message.CMPP_CONNECT:
                cmppConnectedReponse(ctx, msg);
                break;
            case CMPP3Message.CMPP_ACTIVE_TEST:
                cmppActiveTestReponse(ctx);
                break;
            case CMPP3Message.CMPP_SUBMIT:
                cmppSubmitReponse(ctx, msg);
                break;
        }
    }

    private void cmppSubmitReponse(ChannelHandlerContext ctx, CMPP3Message message) {
        logger.info("cmppSubmitReponse................. phone is {}", ((CMPP3Submit) message.getBody()).getDestTerminalId());
        CMPP3Message submitMessageRepo = new CMPP3Message();
        CMPP3SubmitResp submitResp = new CMPP3SubmitResp();
        submitResp.setMessageId(MESSAGEIDSEED.getAndIncrement());
        boolean b = checkSubmit(message, submitResp);
        CMPPHeader header = new CMPPHeader();
        header.setCommandID(CMPP3Message.CMPP_SUBMIT_RESP);
        submitMessageRepo.setHeader(header);
        submitMessageRepo.setBody(submitResp);
        submitMessageRepo.setSequenceId(message.getSequenceId());
        ctx.writeAndFlush(submitMessageRepo);
        deliver(ctx, message, submitResp.getMessageId());
    }


    //上行回复
    private void deliver(ChannelHandlerContext ctx, CMPP3Message message, long messageId) {
        logger.info("deliver.................");
        CMPP3Submit body = (CMPP3Submit) message.getBody();
        String accessNumber = body.getSrcId();
        String[] phones = body.getDestTerminalId();
        for (String phone : phones) {
            CMPP3Message deliverMessage = new CMPP3Message();
            CMPP3Deliver deliver = new CMPP3Deliver();
            deliverMessage.setBody(deliver);
            deliver.setDestId(accessNumber);
            byte isDelivery = 1;
            deliver.setMessageFormat(CharsetInfo.GBK);
            deliver.setSubmitTime(String.format("%010d", CMPPMessageTool.getMMDDHHMMSS()));
            deliver.setDoneTime(String.format("%010d", CMPPMessageTool.getMMDDHHMMSS()));
            deliver.setDestTerminalId(phone);
            deliver.setIsDelivery(isDelivery);
            deliver.setReportMessageId(messageId);
            deliver.setMessageId(messageId);
            deliver.setSrcTerminalId(phone);
            deliver.setMessageContent("你好。。。。。");
            deliver.setStat(getChance() ? "DELIVRD" : "UNDELIV");
            CMPPHeader cmppHeader = new CMPPHeader();
            deliverMessage.setHeader(cmppHeader);
            deliverMessage.setCommandID(CMPP3Message.CMPP_DELIVER);
            cmppHeader.setSequenceId(message.getSequenceId());
            ctx.writeAndFlush(deliverMessage);
        }
    }

    public static boolean getChance() {
        Random random = new Random();
        int i = random.nextInt(99);
        if (i % 2 == 0) {
            return true;
        } else {
            return false;
        }
    }


    //验证入参信息
    private boolean checkSubmit(CMPP3Message message, CMPP3SubmitResp submitResp) {
        byte result = 0;
        submitResp.setResult(result);
        return true;
    }

    private void cmppActiveTestReponse(ChannelHandlerContext ctx) {
        CMPP3Message activeMessage = new CMPP3Message();
        CMPP3ActiveTestResp activeTestResp = new CMPP3ActiveTestResp();
        activeMessage.setBody(activeTestResp);
        activeMessage.setCommandID(CMPP3Message.CMPP_ACTIVE_TEST_RESP);
        ctx.writeAndFlush(activeMessage);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.info("CmppServerHandler exceptionCaught  {}", cause.getMessage());
    }

    /**
     * 处理登录请求
     */
    private void cmppConnectedReponse(ChannelHandlerContext ctx, CMPP3Message request) {
        //验证登录请求信息是否正确并响应
        if (checkUser(request)) {
            CMPP3Message connectedMessage = new CMPP3Message();
            CMPP3ConnectionResp connectionResp = new CMPP3ConnectionResp();
            connectionResp.setStatus(0);
            connectedMessage.setCommandID(CMPP3Message.CMPP_CONNECT_RESP);
            connectedMessage.setSequenceId(request.getSequenceId());
            connectedMessage.setBody(connectionResp);
            ctx.writeAndFlush(connectedMessage);
        }
    }

    private boolean checkUser(CMPP3Message request) {
        CMPP3Connection body = (CMPP3Connection) request.getBody();
        String spId = body.getSpId();
        logger.info("checkUser spId is {}  and account is {}", spId, account);
        if (StringUtils.isNumeric(spId.trim())) {
            account = Integer.valueOf(spId.trim());
        } else {
            account = 100;
        }
        logger.info("checkUser account is {}", account);
        //鉴别ISMG
        return true;
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        /*if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            //读空闲事件，触发重连，关闭当前连接；否则发送心跳包给服务器
            if (event.state().equals(IdleState.READER_IDLE)) {
                logger.info(" server 读空闲事件，连接关闭！");
                ctx.close();
            } else {
                logger.info("server 心跳测试。");
                CMPP3Message message = new CMPP3Message();
                message.setCommandID(CMPP3Message.CMPP_ACTIVE_TEST);
                message.setSequenceId((int) MESSAGEIDSEED.incrementAndGet());
                CMPP3ActiveTest activeTest = new CMPP3ActiveTest();
                message.setBody(activeTest);
                ctx.writeAndFlush(message);
            }
        }*/
    }
}
